﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EzDesk.Apps.Data.Staff;
using EzDesk.Apps.Interface.Staff;
using EzDesk.Apps.Model.Staff;
using EzDesk.Core.Interface;
using EzDesk.Core.Model;
using EzDesk.Core.ServiceImpl.Services;
using EzDesk.Utility;
using EzDesk.Utility.Json;
using EzDesk.Utility.Log;
using EzDesk.Utility.ServiceStatusInfo;

namespace EzDesk.Apps.ServiceImpl.Staff
{
    public class StaffService: IStaffService
    {
        private const string FeedTemplateStr_staff_contractInfoUpdated = "staff_contractInfoUpdated";
        private ICoreAppService _ezApiClient
        {
            get { return new CoreAppService(); }
        }

        #region [ private methods ]
        #region [ feed methods ]
        public void sendContractInfoUpdatedFeed(ContactInfo oldContactInfo, ContactInfo newContactInfo, Guid actorId)
        {
            if (oldContactInfo == null)
            {
                // 防止比较的时候出现null的错误
                oldContactInfo = new ContactInfo();
            }

            // 如果没改 就不发feed
            var isDirty = false;
            var isFirst = true;

            var updateInfoBuilder = new StringBuilder();
            if(!string.IsNullOrEmpty(newContactInfo.MobileNo) && newContactInfo.MobileNo != oldContactInfo.MobileNo)
            {
                updateInfoBuilder.Append("手机号更新为：" + newContactInfo.MobileNo);
                isFirst = false;
                isDirty = true;
            }
            if(!string.IsNullOrEmpty(newContactInfo.QqNumber) && newContactInfo.QqNumber != oldContactInfo.QqNumber)
            {
                if (!isFirst)
                {
                    updateInfoBuilder.Append("<br />");
                }
                updateInfoBuilder.Append("QQ号更新为：" + newContactInfo.QqNumber);
                isDirty = true;
                isFirst = false;
            }
            if(!string.IsNullOrEmpty(newContactInfo.MainEmail) && newContactInfo.MainEmail != oldContactInfo.MainEmail)
            {
                if (!isFirst)
                {
                    updateInfoBuilder.Append("<br />");
                }
                updateInfoBuilder.Append("E-Mail更新为：" + newContactInfo.MainEmail);
                isDirty = true;
                isFirst = false;
            }

            if (!isDirty) return;

            var senderUser = _ezApiClient.GetSimpleUserById(actorId);
            var feedData = new Dictionary<string, string>
                               {
                                   {"senderId", actorId.ToString()},
                                   {"senderName", senderUser.Name},
                                   {"updateInfo", updateInfoBuilder.ToString()},
                               };

            // 发送目标为所有所有人
            var memberString = "everyone";

            var feedId = _ezApiClient.SendFeed(
                FeedTemplateStr_staff_contractInfoUpdated,
                JsonHelper.ConvertToJson(feedData),
                memberString,
                actorId
                );
        }
#endregion


        private ContactInfo getContactInfoByUserId(Guid userId)
        {
            // 保证返回的UserContactInfo不是null
            var staffInfo = getStaffInfoByUserId(userId) ?? new ContactInfo()
            {
                UserId = userId
            };

            return staffInfo;

        }

        #endregion
        
        #region [ Constructors ]
        public StaffService()
        {
            LogEx.TRACE("AttendanceService", "初始化AttendanceService");
        }

        #endregion

        #region [ private methods ]
        private ContactInfo getStaffInfoByUserId(Guid userId)
        {
            var staffInfo = EzDeskStaffContainer.Go(
                container => container.ContactInfoSet.FirstOrDefault(p => p.UserId == userId));
            return staffInfo;
        }
        #endregion


        public StatusInfo<ContactInfo> GetContactInfoByUserId(Guid userId)
        {
            return StatusInfo.Wrap(() => getContactInfoByUserId(userId));
        }

        public StatusInfo<List<ContactInfo>> GetContactInfos(List<SimpleUser> userList)
        {
            return StatusInfo.Wrap(() => (List<ContactInfo>)userList.Select(
                p => getContactInfoByUserId(p.Id))
                                                                 .ToList());
        }

        public StatusInfo UpdateContactInfo(ContactInfo newContactInfo)
        {
            return StatusInfo.Wrap(
                () =>
                    {
                        //todo: 判错
                        var userId = newContactInfo.UserId;
                        var staffInfo = getStaffInfoByUserId(userId);
                        EzDeskStaffContainer.GoAndSave(
                            container =>
                                {
                                    if (staffInfo != null)
                                    {
                                        newContactInfo.Id = staffInfo.Id;
                                        container.ContactInfoSet.Attach(newContactInfo);
                                    }
                                    else
                                    {
                                        newContactInfo.Id = Guid.NewGuid();
                                        container.ContactInfoSet.AddObject(newContactInfo);
                                    }
                                });

                        EzDeskAppApiHelper.DelaySendUpdateFeeds(staffInfo, newContactInfo, newContactInfo.UserId,
                                                                p => p.NewObject.Id == newContactInfo.Id,
                                                                sendContractInfoUpdatedFeed);
                    });
        }

        public List<AppFunction> GetExtraAppFunctions(Guid userId, EzDeskUserAgentType userAgent)
        {
            throw new NotImplementedException();
        }



    }
}
